<template>
  <div class="mall-container">
    <div class="header">
      <div class="left-column">
        <h1 class="mall-title">宠物用品</h1>
        <p class="mall-subtitle">为您的爱宠提供优质商品</p>
        <div class="cart-summary" v-if="store.state.mall.cartList.length > 0">
          <p>购物车共有 {{ cartItemCount }} 件商品（请到“我的订单”查看商品）</p>
        </div>
      </div>

      <div class="right-column">
        <el-input
          v-model="searchText"
          placeholder="请输入搜索内容"
          suffix-icon="el-icon-search"
          @keyup.enter.native="handleSearch"
          @clear="handleSearch"
          clearable
        ></el-input>
        <el-button
          type="primary"
          @click="handleSearch"
          style="margin-left: 10px"
          >搜索</el-button
        >
      </div>
    </div>
    <div class="products-container">
      <div
        v-for="product in filteredProducts"
        :key="product.id"
        class="product-item"
      >
        <img
          :src="`http://127.0.0.1:8000${product.image}`"
          alt="{{ product.name }}"
        />
        <p>{{ product.name }}</p>
        <p>¥{{ product.price }}</p>

        <div
          class="product-footer"
          @click="handleAddToCart(product)"
          v-if="getCartNumber(product.id) == 0"
        >
          <el-icon :size="24" class="cart-icon">
            <ShoppingCart />
          </el-icon>
          <p>加入购物车</p>
        </div>
        <div style="display: flex; margin: 5px; padding: 6px" v-else>
          <el-input-number
            :model-value="getCartNumber(product.id)"
            :min="1"
            :max="10"
            @change="(value) => updateCartNumber(product.id, value)"
          />
          <el-button
            type="danger"
            :icon="Delete"
            circle
            style="margin-left: 15px"
            @click="removeFromCart(product.id)"
          />
        </div>
      </div>
    </div>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        size="small"
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="8"
        :current-page.sync="currentPage"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 已有的模板内容 -->
    <!-- 添加购物车数量显示 -->
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useStore } from "vuex"; // 导入useStore
import { getProductsList } from "../../api/product.js";
import { Delete, ShoppingCart } from "@element-plus/icons-vue";

const store = useStore(); // 创建store实例
const products = ref([]);
const currentPage = ref(1);
const total = ref(0);
const searchText = ref("");
const filteredProducts = ref([]);

// 获取商品在购物车中的数量
const getCartNumber = (productId) => {
  return store.getters["mall/getCartNumber"](productId);
};

// 添加到购物车
const handleAddToCart = (product) => {
  store.dispatch("mall/addToCart", product);
};

// 更新购物车数量
const updateCartNumber = (productId, value) => {
  store.dispatch("mall/updateCartItem", { productId, quantity: value });
};

// 从购物车移除
const removeFromCart = (productId) => {
  store.dispatch("mall/removeFromCart", productId);
};

// 搜索商品
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置到第一页
  fetchProducts(currentPage.value);
};

// 获取商品数据
const fetchProducts = async (page) => {
  try {
    // 显式传递 pageSize 参数为 8
    const data = await getProductsList(page, 8);
    products.value = data.results;
    console.log(products.value);
    // 应用搜索过滤
    if (searchText.value.trim()) {
      const searchLower = searchText.value.toLowerCase();
      filteredProducts.value = products.value.filter(
        (product) =>
          product.name.toLowerCase().includes(searchLower) ||
          product.description?.toLowerCase().includes(searchLower) ||
          product.category?.toLowerCase().includes(searchLower)
      );
      // 搜索时，更新total为过滤后的数量
      total.value = filteredProducts.value.length;
    } else {
      filteredProducts.value = [...products.value];
      total.value = data.count;
    }

    currentPage.value = page;
  } catch (error) {
    console.error("获取商品数据失败:", error);
    products.value = [];
    filteredProducts.value = [];
    total.value = 0;
  }
};

// 初始加载商品数据
onMounted(() => {
  fetchProducts(currentPage.value);
});

// 分页页码变化处理
const handleCurrentChange = (page) => {
  fetchProducts(page);
};

// 计算购物车商品总数
const cartItemCount = computed(() => {
  return store.state.mall.cartList.reduce(
    (total, item) => total + item.quantity,
    0
  );
});
</script>

<style scoped>
.mall-container {
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px 0;
  flex-shrink: 0;
}

.left-column {
  padding-left: 40px;
  display: flex;
  flex-direction: column;
}

.right-column {
  padding-right: 40px;
  display: flex;
  align-items: center;
}

.mall-title {
  font-size: 24px;
  margin-bottom: 5px;
  color: #333;
}

.mall-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.products-container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center; /* 商品居中排列 */
  gap: 10px;
  margin-bottom: 10px;
}

.product-item {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 4px;
  width: 200px;
  display: flex; /* 使用flex布局 */
  flex-direction: column; /* 垂直排列 */
}

.product-footer {
  display: flex; /* 使用flex布局 */
  align-items: center; /* 垂直居中 */
  width: 130px;
  height: 40px;
  margin-top: 10px;
  padding-left: 10px;
  gap: 10px;
  background-color: #a259ff;
  border-radius: 15px;
  cursor: pointer;
}

.cart-icon {
  color: #8d26e6; /* 设置图标颜色 */
  /* 鼠标悬停时显示手型 */
}

.cart-icon:hover {
  color: #a259ff; /* 悬停时颜色变深 */
  transform: scale(1.1); /* 悬停时稍微放大 */
  transition: all 0.3s ease; /* 添加过渡效果 */
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.cart-summary {
  background-color: #f8f8f8;
  border-radius: 4px;
  text-align: right;
}
</style>
